import re
from django import http
from django.contrib.auth import login
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.http import HttpResponse
# Create your views here.
from django.urls import reverse
from django.views import View

from meiduo.utils.response_code import RETCODE
from .models import User


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                 'count':count})

class MobileCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code':RETCODE.OK,
                                  'errmsg':'OK',
                                  'count':count})


class RegisterView(View):
    '''用户注册'''

    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        '''接收用户发来的注册信息，保存到数据库，返回状态'''
        # 1. 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        # TODO: sms_code  没做
        allow = request.POST.get('allow')

        # 2.校验参数
        # 2.1全局校验
        if not all([username, password, password, mobile, allow]):
            return http.HttpResponseForbidden('缺少必穿参数')
            # 2.2单个校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('用户名请输入５－２０为')

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.HttpResponseForbidden('密码请输入８－２０为')

        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号格式不正确')

        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # ３．保存到数据库
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '写入数据库出错'})

        # 5. 状态保持:  session
        login(request, user)

        # 4.注册成功跳转到首页
        return redirect(reverse('contents:index'))
